package com.titan.demo.common.utils;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantReadWriteLock;

import com.alibaba.dubbo.config.ApplicationConfig;
import com.alibaba.dubbo.config.ReferenceConfig;
import com.alibaba.dubbo.config.RegistryConfig;
import com.titan.demo.common.dao.User;
import com.titan.demo.common.interfaces.IDemoService;

public class ConsumerUtil {
	// 当前应用配置
	private static final ApplicationConfig application = new ApplicationConfig();
	// 连接注册中心配置
	private static final RegistryConfig registry = new RegistryConfig();
//	// 注册服务
//	public String  interfaceService = null;  // 接口类型
//	public String  versionService = "1.0.0";
//	public String  clusterService = null;  // 设置重试次数(不含第一次)

	static  {
		application.setName("consumer.name");
//		registry.setAddress("zookeeper://192.168.128.100:2181");
		registry.setAddress("redis://127.0.0.1:6379");
	}
	
	public static final Map<String, ReferenceConfig> cacheReference = new ConcurrentHashMap<String, ReferenceConfig>();
	private static final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
	private static ReferenceConfig getReference(String interfaceService, String versionService) {
		String key = CommonUtils.toString(interfaceService, ":", versionService);
		rwl.readLock().lock();
		try {
			ReferenceConfig reference = cacheReference.get(key);
			if ( reference==null ) {
				rwl.readLock().unlock();
				rwl.writeLock().lock();
				try {
					reference = cacheReference.get(key);
					if ( reference==null ) {
						// 引用远程服务
						reference = new ReferenceConfig(); // 此实例很重，封装了与注册中心的连接以及与提供者的连接，请自行缓存，否则可能造成内存和连接泄漏
						reference.setApplication(application);
						reference.setRegistry(registry); // 多个注册中心可以用setRegistries()
						reference.setInterface(interfaceService);
						reference.setVersion(versionService);
					}
					rwl.readLock().lock();
				} finally {
					rwl.writeLock().unlock();
				}
			}
			return reference;
		} finally {
			rwl.readLock().unlock();
		}		
	}
	
	
	public static <T> T get(Class<?> interfaceService, String versionService) {
		// 引用远程服务
		ReferenceConfig reference = getReference(interfaceService.getName(), versionService);
		return (T)reference.get();
	}
	
	
	public static void output(IDemoService service) {
		System.out.println(service.sayHello("姓名"));
		List<User> list = service.getUsers();
		if (list != null && list.size() > 0) {
			for (int i = 0; i < list.size(); i++) {
				System.out.println(list.get(i));
			}
		}
		
		try {
//			service.throwException();
		} catch(Exception ex) {
			ex.printStackTrace();
		}
	}
}
